const powerMap = require('../../power/power.js');
const fs = require('fs');

let res = [];

for (let key in powerMap) {
    for (let i = 0; i < powerMap[key].power.length; i++) {
        let item = powerMap[key].power[i];
        if (res.indexOf(item) == -1) {
            res.push(item);
        }
    }
}

// 字节序排序算法
function byteSort(arr) {
  return arr.sort((s1, s2) => {
    const minLen = Math.min(s1.length, s2.length);
    // 逐位比较字符编码
    for (let i = 0; i < minLen; i++) {
      const code1 = s1.charCodeAt(i);
      const code2 = s2.charCodeAt(i);
      if (code1 !== code2) {
        return code1 - code2; // 编码小的排前面
      }
    }
    // 前面字符全同，短字符串排前面
    return s1.length - s2.length;
  });
}

const sorted = byteSort(res);

console.log(sorted);

// -------------- 不需要输出 csv 则禁用这段代码 --------------
function outputCSV(arr) {
    let data = '权限名称,权限标识,\n';
    for (let i = 0; i < arr.length; i++) {
        data += `,${ arr[i] },${ '\n' }`;
    }
    fs.writeFileSync('./power.csv', data);
}
outputCSV(sorted);
// -------------- 不需要输出 csv 则禁用这段代码 --------------
